<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <progress value="0" max="1" id="progress"></progress>
    <form name="form">
      <p>
        姓名
        <input type="text" name="name" value="jack" />
      </p>
      <p>
        附件
        <input type="file" name="thingfile" />
      </p>
      <p>
        <button type="button" name="saveBtn">保存</button>
      </p>
    </form>
    <script>
      const form = document.form;

      form.saveBtn.onclick = function () {
        //收集表单信息
        const fd = new FormData();
        fd.append("name", form.name.value);
        fd.append("thingfile", form.thingfile.files[0]);

        // 将数据发送服务器
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "http://127.0.0.1:3000/upload");

        xhr.onload = function () {
          console.log(xhr.response);
        };

        xhr.upload.onloadstart = function () {
          console.log("开始上传");
        };
        xhr.upload.onprogress = function (e) {
          console.log(e.loaded, e.total);
          document.getElementById("progress").value = e.loaded / e.total;
        };
        xhr.upload.error = function (en) {
          console.log("error");
        };
        xhr.upload.onload = function (en) {
          console.log("上传成功");
        };
        xhr.upload.ontimeout = function (en) {
          console.log("上传超时");
        };
        xhr.upload.onloadend = function (en) {
          console.log("上传完成");
        };
        xhr.send(fd);
      };
    </script>
  </body>
</html>
